package com.qbw.app.module.vehicle.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.Observable;
import android.graphics.Point;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.SeekBar;

import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.Projection;
import com.baidu.mapapi.model.LatLng;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.MarkerOptions;
import com.http.okhttp.HttpTask;
import com.lib.util.ScreenUtil;
import com.qbw.actionmanager.ActionManager;
import com.qbw.app.Constant;
import com.qbw.app.R;
import com.qbw.app.action.ElectricAreaAddAction;
import com.qbw.app.action.ElectricAreaDeleteAction;
import com.qbw.app.action.ElectricAreaUpdateAction;
import com.qbw.app.action.ElectricAreaWarningModeSelectedAction;
import com.qbw.app.action.VehicleSelectedAction;
import com.qbw.app.databinding.VehicleActivityAddElectricAreaBinding;
import com.qbw.app.manager.LocationManager;
import com.qbw.app.manager.MapManager;
import com.qbw.app.model.ElectricArea;
import com.qbw.app.model.ElectricAreaDetail;
import com.qbw.app.model.Vehicle;
import com.qbw.app.module.common.activity.CommonActivity;
import com.qbw.app.module.common.fragment.InputDialogFragment;
import com.qbw.app.module.common.util.BaiduUtil;
import com.qbw.app.module.common.util.Gps;
import com.qbw.app.module.common.util.HttpRequestUtil;
import com.qbw.app.module.common.util.PositionUtil;
import com.qbw.app.module.common.util.UniversalToastUtil;
import com.qbw.app.request.impl.VehicleRequest;
import com.qbw.core.observable.ObservableBoolean;
import com.qbw.core.observable.ObservableInt;
import com.qbw.core.observable.ObservableString;
import com.qbw.l.L;
import com.qbw.log.XLog;
import com.qbw.spm.P;

import java.util.ArrayList;

import static com.qbw.app.Constant.KEY_MAP;
import static com.qbw.app.Constant.MAP_BAIDU;
import static com.qbw.app.Constant.MAP_DEFAULT;

/**
 * @author QBW
 * @date 2019/9/27
 */
public class VehicleAddElectricAreaActivity extends CommonActivity<VehicleActivityAddElectricAreaBinding> implements InputDialogFragment.Listener, BaiduUtil.Callback, OnMapReadyCallback {

    private final int MAX_RADIUS_METER = 5000;
    private final int MIN_RADIUS_METER = 50;
    private final int INIT_RADIUS_METER = 2500;
    private GoogleMap mGoogleMap;
    private Handler mHandler = new Handler();
    private ObservableInt mRadiusProgress = new ObservableInt();
    private ObservableInt mRadius = new ObservableInt(0);
    private ObservableString mName = new ObservableString();
    private ObservableString mAddress = new ObservableString();
    private ObservableString mVehicleSelected = new ObservableString();
    private ObservableString mMode = new ObservableString();
    private ObservableBoolean mEnabled = new ObservableBoolean(true);
    private boolean mUseBaidu;
    private LatLng mBaiduCenterGps;
    private com.google.android.gms.maps.model.LatLng mGoogleCenterGps;
    private Vehicle.VehicleList mVehicleList = new Vehicle.VehicleList();
    private ElectricArea.Mode.ModeList mModeList;
    private long mFenceId;

    private ElectricArea mElectricArea;

    public static void start(Context context) {
        start(context, 0);
    }

    public static void start(Context context, ElectricArea electricArea) {
        Intent intent = new Intent(context, VehicleAddElectricAreaActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(Constant.KEY_FENCE, electricArea);
        context.startActivity(intent);
    }

    public static void start(Context context, long fenceId) {
        Intent intent = new Intent(context, VehicleAddElectricAreaActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(Constant.KEY_FENCEID, fenceId);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.vehicle_activity_add_electric_area;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = savedInstanceState == null ? getIntent().getExtras() : savedInstanceState;
        mFenceId = args.getLong(Constant.KEY_FENCEID);
        mElectricArea = (ElectricArea) args.getSerializable(Constant.KEY_FENCE);
        if (mElectricArea != null) {
            mFenceId = mElectricArea.getFenceId();
        }
        mModeList = new ElectricArea.Mode.ModeList();
        mModeList.setList(new ArrayList<>());
        mModeList.getList().add(new ElectricArea.Mode(Constant.ELECTRIC_AREA_MODE_IN));
        mModeList.getList().add(new ElectricArea.Mode(Constant.ELECTRIC_AREA_MODE_OUT));
        mUseBaidu = P.getString(KEY_MAP, MAP_DEFAULT).equals(MAP_BAIDU);
        mBinding.title.setListener(this);
        //0~4500(会在progress的基础上加上最小值50)
        mBinding.sbRadius.setMax(MAX_RADIUS_METER - MIN_RADIUS_METER);
        int initProgress = /*mFenceId > 0 ? MIN_RADIUS_METER : */INIT_RADIUS_METER;
        if (mFenceId <= 0) {
            mBinding.sbRadius.setProgress(initProgress - MIN_RADIUS_METER);
        } else {
            mBinding.tvNowRadius.setVisibility(View.INVISIBLE);
            mBinding.title.setTitle(R.string.electric_area_detail);
        }
        mRadiusProgress.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                updateNowRadiusLeftMargin();
            }
        });
        mRadiusProgress.setValue(initProgress);

        mBinding.sbRadius.getViewTreeObserver()
                         .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                             @Override
                             public void onGlobalLayout() {
                                 mBinding.sbRadius.getViewTreeObserver()
                                                  .removeOnGlobalLayoutListener(this);
                                 updateNowRadiusLeftMargin();
                             }
                         });

        mBinding.sbRadius.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                onRadiusChnaged();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        mBinding.setProgress(mRadiusProgress);
        mBinding.setRadius(mRadius);
        mBinding.setName(mName);
        mBinding.setAddress(mAddress);
        mVehicleSelected.setValue(gs(R.string.all_vehicle));
        mBinding.setVehicleSelected(mVehicleSelected);
        mMode.setValue(gs(R.string.mode_in) + "," + gs(R.string.mode_out));
        mBinding.setMode(mMode);
        if (mElectricArea != null) {
            mEnabled.setValue(mElectricArea.getFenceState() == Constant.ELECTRIC_AREA_STATE_OPEN);
        }
        mBinding.setEnabled(mEnabled);
        mBinding.executePendingBindings();
        initMap();
        mBinding.tvName.setOnClickListener(this);
        mBinding.flNavigation.setOnClickListener(this);
        mBinding.tvVehicle.setOnClickListener(this);
        mBinding.tvWarningMode.setOnClickListener(this);
        ActionManager.getInstance().addInterestedAction(this, VehicleSelectedAction.class);
        ActionManager.getInstance()
                     .addInterestedAction(this, ElectricAreaWarningModeSelectedAction.class);
        mBinding.tvDelete.setVisibility(mFenceId > 0 ? View.VISIBLE : View.GONE);
        mBinding.tvDelete.setOnClickListener(this);
    }


    private void updateNowRadiusLeftMargin() {
        int offset = ScreenUtil.dp2px(VehicleAddElectricAreaActivity.this, 40);
        int sbWidth = mBinding.sbRadius.getWidth();
        int leftMargin = (int) (mRadiusProgress.getValue() / 5000f * sbWidth);
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mBinding.tvNowRadius.getLayoutParams();
        params.leftMargin = offset + leftMargin - mBinding.tvNowRadius.getWidth() / 2;
        mBinding.tvNowRadius.setLayoutParams(params);
    }

    private void afterMapInited() {
        if (mFenceId <= 0) {
            mHandler.post(mToCurrentLocation);
        }
        //mHandler.postDelayed(mRunnInitRadius, 1000);
        mHandler.post(mRunnInitRadius);
    }

    private void afterRadiusInited() {
        //showLoadingDialog("");
        mGeneralManager.getRequestManager().getVehicleRequest().getVehicleList(this).execute();
        /*if (mFenceId <= 0) {
            //添加电子围栏
            mGeneralManager.getRequestManager().getVehicleRequest().getVehicleList(this).execute();
        } else {
            //电子围栏详情
            mGeneralManager.getRequestManager()
                           .getVehicleRequest()
                           .getElectricAreaDetail(mFenceId, this)
                           .execute();
        }*/
    }

    @Override
    public void onRightAreaClick() {
        super.onRightAreaClick();
        if (TextUtils.isEmpty(mName.getValue())) {
            UniversalToastUtil.showToast(R.string.electric_area_name_hint);
            return;
        }
        int radiusOfMeter = mBinding.sbRadius.getProgress() + MIN_RADIUS_METER;
        Gps gps;
        if (mUseBaidu) {
            if (mBaiduCenterGps == null) {
                L.GL.e("mBaiduCenterGps=null");
                return;
            }
            gps = PositionUtil.bd09_To_Gps84(mBaiduCenterGps.latitude, mBaiduCenterGps.longitude);
        } else {
            if (mGoogleCenterGps == null) {
                L.GL.e("mGoogleCenterGps=null");
                return;
            }
            gps = PositionUtil.gcj_To_Gps84(mGoogleCenterGps.latitude, mGoogleCenterGps.longitude);
        }
        showLoadingDialog("");
        if (mFenceId <= 0) {
            mGeneralManager.getRequestManager()
                           .getVehicleRequest()
                           .addElectricArea(gps.getWgLat(),
                                            gps.getWgLon(),
                                            radiusOfMeter,
                                            mName.getValue(),
                                            mEnabled.isValue() ? Constant.ELECTRIC_AREA_STATE_OPEN : Constant.ELECTRIC_AREA_STATE_CLOSE,
                                            mModeList.getSlectedModeParams(),
                                            mVehicleList.getSelectedVehicleCodes(),
                                            this)
                           .execute();
        } else {
            mGeneralManager.getRequestManager()
                           .getVehicleRequest()
                           .updateElectricArea(mFenceId,
                                               gps.getWgLat(),
                                               gps.getWgLon(),
                                               radiusOfMeter,
                                               mName.getValue(),
                                               mEnabled.isValue() ? Constant.ELECTRIC_AREA_STATE_OPEN : Constant.ELECTRIC_AREA_STATE_CLOSE,
                                               mModeList.getSlectedModeParams(),
                                               mVehicleList.getSelectedVehicleCodes(),
                                               this)
                           .execute();
        }
    }

    /**
     * 初始化电子围栏半径，之后修改电子围栏半径之后，ui上显示的半径不会变化了，会去缩放地图
     */
    private boolean initRadius() {
        int radiusOfMeter = /*mBinding.sbRadius.getProgress() + MIN_RADIUS_METER*/INIT_RADIUS_METER;
        if (mUseBaidu) {
            Projection projection = mBinding.bmapView.getMap().getProjection();
            if (projection == null) {
                L.GL.w("baidu projection is null");
                return false;
            }
            float pixel = projection.metersToEquatorPixels(radiusOfMeter);
            mRadius.setValue((int) pixel);
            L.GL.d("radius[%d]", mRadius.getValue());
        } else {
            if (mGoogleMap == null) {
                L.GL.w("google map is null");
                return false;
            }
            if (mGoogleCenterGps == null) {
                L.GL.w("mGoogleCenterGps is null");
                return false;
            }
            float pixel = googleMetersToEquatorPixels(mGoogleMap, mGoogleCenterGps, radiusOfMeter);
            mRadius.setValue((int) pixel);
            L.GL.d("radius[%d]", mRadius.getValue());
        }
        return true;
    }

    private Runnable mRunnInitRadius = new Runnable() {
        @Override
        public void run() {
            if (!initRadius()) {
                mHandler.postDelayed(mRunnInitRadius, 1000);
            } else {
                afterRadiusInited();
            }
        }
    };

    private void onRadiusChnaged() {
        if (mUseBaidu) {
            if (mBaiduCenterGps == null) {
                L.GL.w("mBaiduCenterGps == null");
                return;
            }
            Projection projection = mBinding.bmapView.getMap().getProjection();
            Point center = projection.toScreenLocation(mBaiduCenterGps);
            int nowProgress = mBinding.sbRadius.getProgress() + MIN_RADIUS_METER;
            int radius = (int) projection.metersToEquatorPixels(nowProgress);
            mRadiusProgress.setValue(nowProgress);
            int initRadius = mRadius.getValue();
            int mapHeight = mBinding.bmapView.getHeight();
            int top = (mapHeight - initRadius * 2) / 2;
            Point leftP = new Point(center.x - radius, center.y);
            Point topP = new Point(center.x, center.y - radius - top);
            Point rightP = new Point(center.x + radius, center.y);
            Point bottomP = new Point(center.x, center.y + radius + top);
            LatLng _left = projection.fromScreenLocation(leftP);
            LatLng _top = projection.fromScreenLocation(topP);
            LatLng _right = projection.fromScreenLocation(rightP);
            LatLng _Bottom = projection.fromScreenLocation(bottomP);
            com.baidu.mapapi.model.LatLngBounds.Builder builder = new com.baidu.mapapi.model.LatLngBounds.Builder();
            builder.include(_left);
            builder.include(_top);
            builder.include(_right);
            builder.include(_Bottom);
            mBinding.bmapView.getMap()
                             .setMapStatus(MapStatusUpdateFactory.newLatLngBounds(builder.build()));
        } else {
            if (mGoogleMap == null || mGoogleCenterGps == null) {
                return;
            }
            com.google.android.gms.maps.Projection projection = mGoogleMap.getProjection();
            Point center = /*projection.toScreenLocation(mGoogleCenterGps)*/new Point(mBinding.googleMapView
                                                                                              .getWidth() / 2,
                                                                                      mBinding.googleMapView
                                                                                              .getHeight() / 2);
            int nowProgress = mBinding.sbRadius.getProgress() + MIN_RADIUS_METER;
            int radius = googleMetersToEquatorPixels(mGoogleMap, mGoogleCenterGps, nowProgress);
            mRadiusProgress.setValue(nowProgress);
            int initRadius = mRadius.getValue();
            int mapHeight = mBinding.googleMapView.getHeight();
            int top = (mapHeight - initRadius * 2) / 2;
            L.GL.d("radius[%d], initRadius[%d], top[%d], mapHeight[%d], center.x[%d], center.y[%d]",
                   radius,
                   initRadius,
                   top,
                   mapHeight,
                   center.x,
                   center.y);
            Point leftP = new Point(center.x - radius, center.y);
            Point topP = new Point(center.x, center.y - radius - top);
            Point rightP = new Point(center.x + radius, center.y);
            Point bottomP = new Point(center.x, center.y + radius + top);
            com.google.android.gms.maps.model.LatLng _left = projection.fromScreenLocation(leftP);
            com.google.android.gms.maps.model.LatLng _top = projection.fromScreenLocation(topP);
            com.google.android.gms.maps.model.LatLng _right = projection.fromScreenLocation(rightP);
            com.google.android.gms.maps.model.LatLng _Bottom = projection.fromScreenLocation(bottomP);
            com.google.android.gms.maps.model.LatLngBounds.Builder builder = com.google.android.gms.maps.model.LatLngBounds
                    .builder();
            builder.include(_left);
            builder.include(_top);
            builder.include(_right);
            builder.include(_Bottom);
            CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(builder.build(), 0);
            mGoogleMap.moveCamera(cu);
        }
    }

    public static int googleMetersToEquatorPixels(GoogleMap map,
                                                  com.google.android.gms.maps.model.LatLng base,
                                                  float meters) {
        final double OFFSET_LON = 0.5d;

        Location baseLoc = new Location("");
        baseLoc.setLatitude(base.latitude);
        baseLoc.setLongitude(base.longitude);

        Location dest = new Location("");
        dest.setLatitude(base.latitude);
        dest.setLongitude(base.longitude + OFFSET_LON);

        double degPerMeter = OFFSET_LON / baseLoc.distanceTo(dest); // 1m は何度？
        double lonDistance = meters * degPerMeter; // m を度に変換

        com.google.android.gms.maps.Projection proj = map.getProjection();
        Point basePt = proj.toScreenLocation(base);
        Point destPt = proj.toScreenLocation(new com.google.android.gms.maps.model.LatLng(base.latitude,
                                                                                          base.longitude + lonDistance));

        L.GL.d("degPerMeter[%f], lonDistance[%f], destPt.x[%d], basePt.x[%d]",
               degPerMeter,
               lonDistance,
               destPt.x,
               basePt.x);
        return Math.abs(destPt.x - basePt.x);
    }

    private void initMap() {
        if (mUseBaidu) {
            initBaidu();
        } else {
            initGoogle();
        }
    }

    private void initBaidu() {
        mBinding.bmapView.setVisibility(View.VISIBLE);
        mBinding.bmapView.showScaleControl(false);
        mBinding.bmapView.showZoomControls(false);

        BaiduMap map = mBinding.bmapView.getMap();
        map.setMyLocationEnabled(true);
        map.setMyLocationConfiguration(new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL,
                                                                   true,
                                                                   BitmapDescriptorFactory.fromResource(
                                                                           R.drawable.travel_offline)));
        //map.setOnMapClickListener(mBadiuMapClickListener);
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(13.8f);
        map.setMapStatus(msu);

        //mLocationClient = new LocationClient(getApplicationContext());
        LocationClientOption option = new LocationClientOption();

        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认gcj02
        //gcj02：国测局坐标；
        //bd09ll：百度经纬度坐标；
        //bd09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回wgs84类型坐标

        option.setScanSpan(1000);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true

        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前WiFi是否超出有效期，若超出有效期，会先重新扫描WiFi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        //mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明

        //mLocationClient.registerLocationListener(mBaiduLocationListener = new
        // ElecAreaAddActivity.MyBaiduLocationListener());

        //mLocationClient.start();
        //mLocationClient.requestLocation();
        /*mBinding.bmapView.getMap().setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                VehicleLocationActivity.start(mContext, mData);
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });
        mBinding.bmapView.getMap().clear();
        baiduAnimateAndAddMarker(mData.getLatitude(), mData.getLongitude(), R.drawable.travel_location);*/
        mBinding.bmapView.getMap()
                         .setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
                             @Override
                             public void onMapStatusChangeStart(MapStatus mapStatus) {
                                 L.GL.d("here");
                             }

                             @Override
                             public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

                             }

                             @Override
                             public void onMapStatusChange(MapStatus mapStatus) {
                                 //L.GL.d("here");
                             }

                             @Override
                             public void onMapStatusChangeFinish(MapStatus mapStatus) {
                                 mBaiduCenterGps = mapStatus.target;
                                 getCurrentCenterPosAddress();
                             }
                         });
        afterMapInited();
    }

    private Runnable mToCurrentLocation = new Runnable() {
        @Override
        public void run() {
            Location location = LocationManager.getInstance().getLastLocation();
            if (location != null && location.getLatitude() != 0 && location.getLongitude() != 0) {
                /*L.GL.e("here");
                setCenterGps(location.getLatitude(), location.getLongitude());*/
                if (mUseBaidu) {
                    Gps gps = PositionUtil.gps84_to_bd09_byBaiduSdk(location.getLatitude(),
                                                                    location.getLongitude());
                    mBaiduCenterGps = new LatLng(gps.getWgLat(), gps.getWgLon());
                    baiduAnimateToPosition(location.getLatitude(), location.getLongitude());
                    getCurrentCenterPosAddress();
                } else {
                    Gps gps = PositionUtil.gps84_To_Gcj02(location.getLatitude(),
                                                          location.getLongitude());
                    mGoogleCenterGps = new com.google.android.gms.maps.model.LatLng(gps.getWgLat(),
                                                                                    gps.getWgLon());
                    googleAnimateToPosition(location.getLatitude(), location.getLongitude());
                    getCurrentCenterPosAddress();
                }
            } else {
                L.GL.w("last location is invalid!");
                mHandler.postDelayed(mToCurrentLocation, 1000);
            }
        }
    };

    /**
     * @param lat gps84
     * @param lng gps84
     */
    private void toThisPosition(double lat, double lng) {
        /*L.GL.e("here");
        setCenterGps(lat, lng);*/
        if (mUseBaidu) {
            Gps gps = PositionUtil.gps84_to_bd09_byBaiduSdk(lat, lng);
            mBaiduCenterGps = new LatLng(gps.getWgLat(), gps.getWgLon());
            baiduAnimateToPosition(lat, lng);
            getCurrentCenterPosAddress();
        } else {
            Gps gps = PositionUtil.gps84_To_Gcj02(lat, lng);
            mGoogleCenterGps = new com.google.android.gms.maps.model.LatLng(gps.getWgLat(),
                                                                            gps.getWgLon());
            googleAnimateToPosition(lat, lng);
            getCurrentCenterPosAddress();
        }
    }

    private void setCenterGps(double gps84Lat, double gps84Lng) {
        L.GL.e("gps84Lat[%f],gps84Lng[%f]", gps84Lat, gps84Lng);
    }

    private void baiduAnimateToPosition(double lat, double lon) {
        Gps gps = PositionUtil.gps84_to_bd09_byBaiduSdk(lat, lon);
        MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(new LatLng(gps.getWgLat(),
                                                                             gps.getWgLon()));
        // 移动到某经纬度
        mBinding.bmapView.getMap().animateMapStatus(update);

    }

    /**
     * 移动到指定位置，并添加marker
     */
    private void baiduAnimateAndAddMarker(double latitude,
                                          double longitude,
                                          int positionDrawableRes) {
        Gps gps = PositionUtil.gps84_To_Bd09(latitude, longitude);
        MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(new LatLng(gps.getWgLat(),
                                                                             gps.getWgLon()));
        // 移动到某经纬度
        mBinding.bmapView.getMap().animateMapStatus(update);

        //添加marker
        mBinding.bmapView.getMap()
                         .addOverlay(new com.baidu.mapapi.map.MarkerOptions().position(new LatLng(
                                 gps.getWgLat(),
                                 gps.getWgLon()))
                                                                             .icon(BitmapDescriptorFactory
                                                                                           .fromResource(
                                                                                                   positionDrawableRes)))
                         .setZIndex(4);
    }

    private void googleAnimateToPosition(double lat, double lon) {
        if (mGoogleMap == null) {
            XLog.e("mGoogleMap == null");
            return;
        }
        Gps gps = PositionUtil.gps84_To_Gcj02(lat, lon);
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(new com.google.android.gms.maps.model.LatLng(
                gps.getWgLat(),
                gps.getWgLon()));
        mGoogleMap.moveCamera(cameraUpdate);
    }

    private void googleAnimateAndAddMarker(double latitude,
                                           double longitude,
                                           int positionDrawableRes) {
        Gps _gps = PositionUtil.gps84_To_Gcj02(latitude, longitude);
        // 移动到某经纬度
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new com.google.android.gms.maps.model.LatLng(
                _gps.getWgLat(),
                _gps.getWgLon()), 11);
        mGoogleMap.moveCamera(cameraUpdate);

        //添加marker
        mGoogleMap.addMarker(new MarkerOptions().icon(com.google.android.gms.maps.model.BitmapDescriptorFactory
                                                              .fromResource(positionDrawableRes))
                                                .position(new com.google.android.gms.maps.model.LatLng(
                                                        _gps.getWgLat(),
                                                        _gps.getWgLon()))).setZIndex(4);
    }

    private void initGoogle() {
        mBinding.googleMapView.setVisibility(View.VISIBLE);
        mBinding.googleMapView.onCreate(null);
        mBinding.googleMapView.getMapAsync(this);
    }

    private void getCurrentCenterPosAddress() {
        if (mUseBaidu) {
            Gps gps = PositionUtil.bd09_To_Gps84(mBaiduCenterGps.latitude,
                                                 mBaiduCenterGps.longitude);
            new BaiduUtil(this).getAddress(gps.getWgLat(), gps.getWgLon(), null);
        } else {
            Gps gps = PositionUtil.gcj_To_Gps84(mGoogleCenterGps.latitude,
                                                mGoogleCenterGps.longitude);
            new BaiduUtil(this).getAddress(gps.getWgLat(), gps.getWgLon(), null);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mUseBaidu) {
        } else {
            mBinding.googleMapView.onStart();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mUseBaidu) {
            mBinding.bmapView.onResume();
        } else {
            mBinding.googleMapView.onResume();
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int vid = v.getId();
        if (vid == R.id.tv_name) {
            InputDialogFragment.createInstance(vid,
                                               gs(R.string.electric_area_name),
                                               gs(R.string.electric_area_name_hint),
                                               gs(R.string.save),
                                               mName.getValue(),
                                               0).show(getSupportFragmentManager(), "name");
        } else if (vid == R.id.fl_navigation) {
            if (!LocationManager.getInstance().isGpsOpened(this)) {
                UniversalToastUtil.showToast(R.string.please_open_gps);
                return;
            }
            //地图移动到当前用户位置
            mHandler.removeCallbacks(mToCurrentLocation);
            mHandler.post(mToCurrentLocation);
        } else if (vid == R.id.tv_vehicle) {
            VehicleSelectActivity.start(this, mVehicleList);
        } else if (vid == R.id.tv_warning_mode) {
            VehicleElectricAreaWarningModeSelectActivity.start(this, mModeList);
        } else if (vid == R.id.tv_delete) {
            showLoadingDialog("");
            mGeneralManager.getRequestManager()
                           .getVehicleRequest()
                           .deleteElectricArea(mFenceId, this)
                           .execute();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mUseBaidu) {
            mBinding.bmapView.onPause();
        } else {
            mBinding.googleMapView.onPause();
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;
        mGoogleMap.getUiSettings().setCompassEnabled(false);
        CameraUpdate cameraUpdate = CameraUpdateFactory.zoomTo(12);
        mGoogleMap.moveCamera(cameraUpdate);
        mGoogleMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
            @Override
            public void onCameraIdle() {
                com.google.android.gms.maps.model.LatLng center = mGoogleMap.getCameraPosition().target;
                if (center.latitude == 0 || center.longitude == 0) {
                    L.GL.w("invalid latitude:%f, longitude:%f", center.latitude, center.longitude);
                    return;
                }
                /*L.GL.e("here");
                Gps gps = PositionUtil.gcj_To_Gps84(center.latitude, center.longitude);
                setCenterGps(gps.getWgLat(), gps.getWgLon());*/
                //Gps gps = PositionUtil.gps84_To_Gcj02(center.latitude, center.longitude);
                mGoogleCenterGps = new com.google.android.gms.maps.model.LatLng(center.latitude,
                                                                                center.longitude);
                mHandler.removeCallbacks(mRunnGetCenterGps);
                mHandler.postDelayed(mRunnGetCenterGps, 500);
            }
        });
        /*mGoogleMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
            @Override
            public void onCameraMove() {
                com.google.android.gms.maps.model.LatLng center = mGoogleMap.getCameraPosition().target;
                if (center.latitude == 0 || center.longitude == 0) {
                    L.GL.w("invalid latitude:%f, longitude:%f", center.latitude, center.longitude);
                    return;
                }
                L.GL.e("here");
                Gps gps = PositionUtil.gcj_To_Gps84(center.latitude,center.longitude);
                setCenterGps(gps.getWgLat(),gps.getWgLon());
            }
        });*/
        mHandler.post(mToCurrentLocation);
        mHandler.post(mRunnInitRadius);
        afterMapInited();
    }

    private Runnable mRunnGetCenterGps = new Runnable() {
        @Override
        public void run() {
            getCurrentCenterPosAddress();
        }
    };

    @Override
    public void onActionTriggered(Object action) {
        super.onActionTriggered(action);
        if (action instanceof VehicleSelectedAction) {
            mVehicleList = ((VehicleSelectedAction) action).getAction();
            if (mVehicleList.isAllVehicleSelected()) {
                mVehicleSelected.setValue(gs(R.string.all_vehicle));
            } else {
                mVehicleSelected.setValue(String.format(gs(R.string.vehicle_count_format),
                                                        mVehicleList.getSelectedVehicleList()
                                                                    .size()));
            }
        } else if (action instanceof ElectricAreaWarningModeSelectedAction) {
            mModeList = ((ElectricAreaWarningModeSelectedAction) action).getAction();
            mMode.setValue(mModeList.getSlectedModeNames());
        }
    }

    private void updateMode(String triggerSet) {
        for (ElectricArea.Mode mode : mModeList.getList()) {
            mode.setSelected(triggerSet.contains(mode.getState() + ""));
        }
        mMode.setValue(mModeList.getSlectedModeNames());
    }

    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        super.onHttpSuccess(httpTask, entity);
        String method = httpTask.getMethod();
        if (method.equals(VehicleRequest.METHOD_ELECTRIC_AREA_ADD)) {
            UniversalToastUtil.showRightIconToast(R.string.add_electric_area_success);
            ActionManager.getInstance().triggerAction(new ElectricAreaAddAction(null));
            closeLoadingDialog();
            finish();
        } else if (method.equals(VehicleRequest.METHOD_VEHICLE_LIST)) {
            Vehicle.Response response = (Vehicle.Response) entity;
            mVehicleList = response.getData();
            if (mFenceId <= 0) {
                closeLoadingDialog();
            } else {
                //电子围栏详情
                mGeneralManager.getRequestManager()
                               .getVehicleRequest()
                               .getElectricAreaDetail(mFenceId, this)
                               .execute();
            }
        } else if (method.equals(VehicleRequest.METHOD_ELECTRIC_AREA_DETAIL)) {
            ElectricAreaDetail.Resonse res = (ElectricAreaDetail.Resonse) entity;
            ElectricAreaDetail electricAreaDetail = res.getData();
            //mVehicleList.setList(electricAreaDetail.getVehicles());
            int allSize = mVehicleList == null ? 0 : mVehicleList.size();
            int selectedSize = electricAreaDetail.getVehicles() == null ? 0 : electricAreaDetail.getVehicles()
                                                                                                .size();
            if (allSize > 0 && selectedSize > 0) {
                for (Vehicle v1 : mVehicleList.getList()) {
                    v1.setSelected(false);
                    for (Vehicle v2 : electricAreaDetail.getVehicles()) {
                        if (v1.getVehicleCode().equals(v2.getVehicleCode())) {
                            v1.setSelected(true);
                            break;
                        }
                    }
                }
            }
            //mVehicleSelected.setValue(mVehicleList.getSelectedVehicleNames());
            if (mVehicleList.isAllVehicleSelected()) {
                mVehicleSelected.setValue(gs(R.string.all_vehicle));
            } else {
                mVehicleSelected.setValue(String.format(gs(R.string.vehicle_count_format),
                                                        mVehicleList.getSelectedVehicleList()
                                                                    .size()));
            }
            ElectricAreaDetail.Radius radius = electricAreaDetail.getDetail();
            mRadiusProgress.setValue(radius.getRadius());
            mBinding.sbRadius.setProgress(radius.getRadius() - MIN_RADIUS_METER);
            toThisPosition(radius.getLatitude(), radius.getLongitude());
            mName.setValue(electricAreaDetail.getFenceName());
            updateMode(electricAreaDetail.getTriggerSet());
            mEnabled.setValue(Constant.ELECTRIC_AREA_STATE_OPEN == electricAreaDetail.getFenceState());
            /*mBinding.sc.setChecked(mEnabled.isValue());
            mBinding.sc.jumpDrawablesToCurrentState();*/
            if (MapManager.getInstance().isUseBaidu()) {
                mBinding.bmapView.postDelayed(() -> onRadiusChnaged(), 100);
                mBinding.bmapView.postDelayed(() -> onRadiusChnaged(), 200);
                mBinding.bmapView.postDelayed(() -> onRadiusChnaged(), 300);
            } else {
                mBinding.googleMapView.postDelayed(() -> onRadiusChnaged(), 100);
                mBinding.googleMapView.postDelayed(() -> onRadiusChnaged(), 200);
                mBinding.googleMapView.postDelayed(() -> onRadiusChnaged(), 300);
            }
            mBinding.tvNowRadius.setVisibility(View.VISIBLE);
            closeLoadingDialog();
        } else if (method.equals(VehicleRequest.METHOD_ELECTRIC_AREA_DELETE)) {
            ActionManager.getInstance().triggerAction(new ElectricAreaDeleteAction(mFenceId));
            closeLoadingDialog();
            finish();
        } else if (method.equals(VehicleRequest.METHOD_ELECTRIC_AREA_UPDATE)) {
            ActionManager.getInstance().triggerAction(new ElectricAreaUpdateAction(mFenceId));
            closeLoadingDialog();
            finish();
        }
    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        super.onHttpFailed(httpTask, errorCode, message);
        message = HttpRequestUtil.getMessage(errorCode, message);
        String method = httpTask.getMethod();
        if (method.equals(VehicleRequest.METHOD_ELECTRIC_AREA_ADD)) {
            UniversalToastUtil.showFailedIconToast(message);
            closeLoadingDialog();
        } else if (method.equals(VehicleRequest.METHOD_VEHICLE_LIST)) {
            UniversalToastUtil.showToast(message);
            closeLoadingDialog();
            finish();
        } else if (method.equals(VehicleRequest.METHOD_ELECTRIC_AREA_DETAIL)) {
            UniversalToastUtil.showToast(message);
            closeLoadingDialog();
            finish();
        } else if (method.equals(VehicleRequest.METHOD_ELECTRIC_AREA_DELETE)) {
            UniversalToastUtil.showToast(message);
            closeLoadingDialog();
            finish();
        } else if (method.equals(VehicleRequest.METHOD_ELECTRIC_AREA_UPDATE)) {
            UniversalToastUtil.showFailedIconToast(message);
            closeLoadingDialog();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putLong(Constant.KEY_FENCEID, mFenceId);
        outState.putSerializable(Constant.KEY_FENCE, mElectricArea);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActionManager.getInstance().removeInterestedActions(this);
        mHandler.removeCallbacks(mToCurrentLocation);
        mHandler.removeCallbacks(mRunnInitRadius);
        if (mUseBaidu) {
            mBinding.bmapView.onDestroy();
        } else {
            mBinding.googleMapView.onDestroy();
        }
    }

    @Override
    public void onGetPointAddress(boolean success, String addr, Object extra) {
        mAddress.setValue(addr);
    }

    @Override
    public void onClickInputOk(int type, String inputContent) {
        mName.setValue(inputContent);
    }

    @Override
    public void onClickInputCancel(int type) {

    }
}
